package id.co.shuba.spamobile.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.Configs;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.IDatePickerDialog;
import id.co.shuba.spamobile.IDatePickerTarget;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.data.AuditDB;
import id.co.shuba.spamobile.data.DSARDB;
import id.co.shuba.spamobile.data.DatabaseHandler;
import id.co.shuba.spamobile.data.HolidayDB;
import id.co.shuba.spamobile.data.HolidayDB;
import id.co.shuba.spamobile.data.StandardDB;
import id.co.shuba.spamobile.data.ProspectDB;
import id.co.shuba.spamobile.data.ProspectProgressDB;
import id.co.shuba.spamobile.data.TransactionLogDB;
import id.co.shuba.spamobile.dialog.CustomTimePickerDialog;
import id.co.shuba.spamobile.dialog.DatePickerFragment;
import id.co.shuba.spamobile.model.AuditInfo;
import id.co.shuba.spamobile.model.DSARInfo;
import id.co.shuba.spamobile.model.ErrorInfo;
import id.co.shuba.spamobile.model.MaintenanceVisitInfo;
import id.co.shuba.spamobile.model.ProspectInfo;
import id.co.shuba.spamobile.model.ProspectProgressInfo;
import id.co.shuba.spamobile.model.UserInfo;
import id.co.shuba.spamobile.util.AuditUtil;
import id.co.shuba.spamobile.util.DialogUtil;
import id.co.shuba.spamobile.util.SpinnerUtil;
import id.co.shuba.spamobile.util.Str;
import id.co.shuba.spamobile.util.ValidationUtil;
import android.opengl.Visibility;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;

public class FormDSARActivity extends SherlockFragmentActivity implements IDatePickerDialog, IDatePickerTarget {
	private static final int DATE_DIALOG_ID = 212;
	private static final int TIME_DIALOG_ID = 213;
	private static final String RESULT_APPLICATION = "1001";
	private static final String RESULT_NOT_INTERESTED = "1004";
	private static final String RESULT_REJECTED_BY_UNIT = "1002";
	
	private EditText txtVisitPlanDate;
	private EditText txtVisitPlanTime;
	private EditText txtVisitActualDate;
	private EditText txtVisitActualTime;
	private ImageButton btnPickVisitPlanDate;
	private ImageButton btnPickVisitPlanTime;
	private ImageButton btnPickVisitActualDate;
	private ImageButton btnPickVisitActualTime;
	private RadioGroup rbGroup;	
	private RadioButton rbY;
	private RadioButton rbN;
	private Spinner spnPurpose;
	private Spinner spnResult;
	private Spinner spnReason;
	private EditText txtRemark;
	private LinearLayout pnlUpdate;
	private LinearLayout pnlReason;

	private DatabaseHandler _db;
	private DSARDB _dsarDB;
	private StandardDB _optionDB;	
	private ProspectDB _prospectDB;

	private DSARInfo _info;
	private ProspectInfo _prospectInfo;
	private int _visitNo;
	private String _prospectID;
	
	private String defaultOption;	
	
	private MenuItem menuSave;
	
	private static EditText txtDate;
	private static EditText txtTime;    

	private LogoutReceiver logoutReceiver;
	
	private boolean _ro;

	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_form_dsar);
		setUpLogoutReceiver();
		defaultOption = getString(R.string.default_option);
		
		setControls();		

		_db = new DatabaseHandler(this);
		_optionDB = new StandardDB(_db);
		_dsarDB = new DSARDB(_db);
		_prospectDB = new ProspectDB(_db);

		fillSpinner();
						
		Intent intent = getIntent();		
		_visitNo = -1;
		_prospectID = intent.getStringExtra("prospectID");
		_ro = intent.getBooleanExtra("ro", false);
		_prospectInfo = _prospectDB.getFullInfo(_prospectID);			
		
		if (intent.hasExtra("visitNo")) {
			pnlUpdate.setVisibility(View.VISIBLE);
			_visitNo = intent.getIntExtra("visitNo", -1);			
			_info = _dsarDB.get(_prospectID, _visitNo);			
			loadData(_info);
			
			boolean isEditable = isEditable();
			setMode(isEditable);
			
			setTitle((isEditable? "Ubah" : "") + "DSAR" + (_ro? " (Read Only)" : ""));
		} else {						
			setTitle("Buat DSAR");
		}
		
		
		Object obj = getLastCustomNonConfigurationInstance();
		if (obj != null) {		
			Object[] states = (Object[])obj;
			txtDate = (EditText)states[0];
			txtTime = (EditText)states[1];
		}
	}
	
	private EditText getDateDisplay() {
		return txtDate;
	}
	
	private EditText getTimeDisplay() {
		return txtTime;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_form_dsar, menu);

		menuSave = menu.findItem(R.id.menu_save);			
		menuSave.setVisible(isEditable());		
		
        return true;    
	}
	
	private void setMode(boolean editable) {
		//txtVisitPlanDate.setFocusable(editable);
		//txtVisitPlanTime.setFocusable(editable);
		
		txtVisitPlanDate.setFocusable(false);
		txtVisitPlanTime.setFocusable(false);
		
		txtVisitActualDate.setFocusable(editable);
		txtVisitActualTime.setFocusable(editable);
		
		//btnPickVisitPlanDate.setVisibility(editable? View.VISIBLE : View.GONE);
		//btnPickVisitPlanTime.setVisibility(editable? View.VISIBLE : View.GONE);
		
		btnPickVisitPlanDate.setVisibility(View.GONE);
		btnPickVisitPlanTime.setVisibility(View.GONE);
		
		
		btnPickVisitActualDate.setVisibility(editable? View.VISIBLE : View.GONE);
		btnPickVisitActualTime.setVisibility(editable? View.VISIBLE : View.GONE);
				
		
		rbGroup.setEnabled(editable);		
		rbY.setEnabled(editable);
		rbN.setEnabled(editable);
		spnPurpose.setEnabled(editable);
		spnResult.setEnabled(editable);
		spnReason.setEnabled(editable);			
		
		txtRemark.setFocusable(editable);
	}
	
	private boolean isEditable() {
		return _info == null || !_ro;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getTitle().equals("Simpan")) {			
			save();
		}
		
	    return super.onOptionsItemSelected(item);
	}	
	
	private void setControls() {
		txtVisitPlanDate = (EditText) findViewById(R.id.txtVisitPlanDate);
		txtVisitPlanTime = (EditText) findViewById(R.id.txtVisitPlanTime);
		txtVisitActualDate = (EditText) findViewById(R.id.txtVisitActualDate);
		txtVisitActualTime = (EditText) findViewById(R.id.txtVisitActualTime);
		
		btnPickVisitPlanDate = (ImageButton) findViewById(R.id.btnPickVisitPlanDate);
		btnPickVisitPlanTime = (ImageButton) findViewById(R.id.btnPickVisitPlanTime);
		btnPickVisitActualDate = (ImageButton) findViewById(R.id.btnPickVisitActualDate);
		btnPickVisitActualTime = (ImageButton) findViewById(R.id.btnPickVisitActualTime);
		
		rbGroup = (RadioGroup) findViewById(R.id.rbJoinFieldWork);		
		spnPurpose = (Spinner) findViewById(R.id.spnPurpose);
		spnResult = (Spinner) findViewById(R.id.spnResult);
		spnReason = (Spinner) findViewById(R.id.spnReason);		
		pnlUpdate = (LinearLayout) findViewById(R.id.pnlUpdate);		
		pnlReason = (LinearLayout) findViewById(R.id.pnlReason);
		
		rbY = (RadioButton) findViewById(R.id.rbYes);
		rbN = (RadioButton) findViewById(R.id.rbNo);
		
		txtRemark = (EditText) findViewById(R.id.txtRemark);
		
		initReasonSpinner();
	}
	
	private void initReasonSpinner() {
		spnResult.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {				
				setReasonControlVisibility();						
			}
			@Override
			public void onNothingSelected(AdapterView<?> parent) {}
		});
	}
	
	private void fillSpinner() {
		SpinnerUtil.fillStandard(this, _optionDB, spnPurpose, StandardDB.GROUP_OBJECTIVE_OF_VISIT, "D", defaultOption);
		SpinnerUtil.fillStandard(this, _optionDB, spnReason, StandardDB.GROUP_REASON, defaultOption);
		SpinnerUtil.fillStandard(this, _optionDB, spnResult, StandardDB.GROUP_RESULT_OF_VISIT, defaultOption);				
	}

	private void loadData(DSARInfo info) {									
		SpinnerUtil.optionSetSelectedValue(spnPurpose, info.getObjectiveOfVisit());
		SpinnerUtil.optionSetSelectedValue(spnResult, info.getResultOfVisit());
		
		String reason = _prospectInfo.getNotInterestedReason(); 
		if (!Str.isNullOrEmpty(reason))
			SpinnerUtil.optionSetSelectedValue(spnReason, reason);
				
		rbGroup.check("1".equals(info.getJoinFieldWork())? R.id.rbYes : R.id.rbNo);
		
		txtVisitPlanDate.setText(DialogUtil.changeFormat(info.getDateVisitPlan()));
		txtVisitPlanTime.setText(info.getTimeVisitPlan());
		
		if (info.getDateVisitActual() != null && !"2009-01-01".equals(info.getDateVisitActual())) {			
			txtVisitActualDate.setText(DialogUtil.changeFormat(info.getDateVisitActual()));
			txtVisitActualTime.setText(info.getTimeVisitActual());
		}
		
		txtRemark.setText(info.getRemark());
	}

	private DSARInfo getData() {
		UserInfo user = Sessions.getUser(this);
		return getData(user);
	}
	
	private DSARInfo getData(UserInfo user) {
		DSARInfo info = new DSARInfo();		
		info.setProspectID(_prospectID);					
		
		info.setJoinFieldWork(rbGroup.getCheckedRadioButtonId() == R.id.rbYes? "1" : "0");		
		info.setObjectiveOfVisit(SpinnerUtil.optionGetSelectedValue(spnPurpose, defaultOption));
		info.setResultOfVisit(SpinnerUtil.optionGetSelectedValue(spnResult, defaultOption));
		//info.setRemark(SpinnerUtil.optionGetSelectedValue(spnReason, defaultOption));			
		info.setRemark(txtRemark.getText().toString());
		
		info.setDateVisitPlan(DialogUtil.changeFormat(txtVisitPlanDate.getText().toString()));
		info.setTimeVisitPlan(txtVisitPlanTime.getText().toString()); 		
		
		info.setDateVisitActual(DialogUtil.changeFormat(txtVisitActualDate.getText().toString()));
		info.setTimeVisitActual(txtVisitActualTime.getText().toString());
				
		//info.setTimeVisitActual(time);
		
		String date = App.getProcessDateTime();
				
		if (_info == null) {
			info.setEntryBy(user.getNip());
			info.setEntryDate(date);
		} else {
			info.setEntryBy(_info.getEntryBy());
			info.setEntryDate(_info.getEntryDate());
		}	
		
		info.setUpdateBy(user.getNip());
		info.setUpdateDate(date);
		
		info.setIsUpload("0");
		
		return info;
	}

	public void onDateDialogButtonClick(View v) {
		switch (v.getId()) {
		case R.id.btnPickVisitPlanDate:
			txtDate = txtVisitPlanDate;
			break;
		case R.id.btnPickVisitActualDate:
			txtDate = txtVisitActualDate;
			break;
		}
		showDialog(DATE_DIALOG_ID);
	}
	
	public void onTimeDialogButtonClick(View v) {
		switch (v.getId()) {
		case R.id.btnPickVisitPlanTime:
			txtTime = txtVisitPlanTime;
			break;
		case R.id.btnPickVisitActualTime:
			txtTime = txtVisitActualTime;
			break;
		}		
		showDialog(TIME_DIALOG_ID);		
	}
		
	/*
	@Override	
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return DialogUtil.create(this, txtDate);
		case TIME_DIALOG_ID:
			return DialogUtil.createTimePicker(this, txtTime);
		}

		return null;
	}*/
	
	private void setReasonControlVisibility() {
		String status = SpinnerUtil.optionGetSelectedValue(spnResult, defaultOption);
		if (RESULT_NOT_INTERESTED.equals(status)) {
			pnlReason.setVisibility(View.VISIBLE);
		} else {			
			pnlReason.setVisibility(View.GONE);
		}
	}
	
	private List<ErrorInfo> validate(DSARInfo info) {			
		List<ErrorInfo> errors = new ArrayList<ErrorInfo>();
		/*if (!DialogUtil.isValid(info.getDateVisitPlan()))
			errors.add(new ErrorInfo(txtVisitPlanDate, getString(R.string.visit_plan)));*/
		
		if (_info == null && !DialogUtil.isValidAfterward(info.getDateVisitPlan()))
			errors.add(new ErrorInfo(txtVisitPlanDate, getString(R.string.visit_date), "Tanggal rencana kunjungan tidak boleh kurang dari tanggal sekarang"));
		
		if (_info != null) {
			if (!DialogUtil.isValid(info.getDateVisitActual()))
				errors.add(new ErrorInfo(txtVisitActualDate, getString(R.string.visit_actual_date)));			
			/*if (!DialogUtil.isValidAfterward(info.getDateVisitActual(), info.getDateVisitPlan()))
				errors.add(new ErrorInfo(txtVisitActualDate,
						getString(R.string.visit_actual_date) + " < "
				+ getString(R.string.visit_plan)));*/			
			if (!DialogUtil.isValidAfterward(info.getDateVisitActual(), info.getDateVisitPlan())) {
				errors.add(new ErrorInfo(txtVisitActualDate,
						getString(R.string.visit_actual_date), "Tanggal kunjungan aktual harus lebih besar dari tanggal rencana kunjungan"));
			} else if (!DialogUtil.isValidAfterward(App.getProcessDate(), info.getDateVisitActual())) {
				errors.add(new ErrorInfo(txtVisitActualDate,
						getString(R.string.visit_actual_date), "Tanggal kunjungan aktual tidak boleh lebih dari tanggal sekarang"));
			}
			if (!"".equals(info.getTimeVisitActual()) && !DialogUtil.isValidTime(info.getTimeVisitActual()))
				errors.add(new ErrorInfo(txtVisitActualTime, getString(R.string.visit_actual_time)));				
			if (info.getObjectiveOfVisit() == null)
				errors.add(new ErrorInfo(spnPurpose, getString(R.string.purpose)));			
			if (info.getResultOfVisit() == null)
				errors.add(new ErrorInfo(spnResult, getString(R.string.result)));						
			if (RESULT_NOT_INTERESTED.equals(info.getResultOfVisit()) && info.getRemark() == null)
				errors.add(new ErrorInfo(spnReason, getString(R.string.reason)));
			if (Str.isNullOrEmpty(info.getRemark()))
				errors.add(new ErrorInfo(txtRemark, "Catatan Kunjungan"));
			
			if (info.getRemark().length() > 255)
				errors.add(new ErrorInfo(txtRemark, "Catatan Kunjungan", "Catatan Kunjungan maksimal 255 karakter"));
		}
		
		return errors;
	}				

	private void save() {				
		final UserInfo user = Sessions.getUser(this);
		final DSARInfo info = getData(user);
		
		if (RESULT_APPLICATION.equals(info.getResultOfVisit()) && Str.isNullOrEmpty(_prospectInfo.getKtpName())) {
			Toast.makeText(this, "Untuk hasil kunjungan 'aplikasi', data pelengkap harus diisi terlebih dahulu.", Toast.LENGTH_LONG).show();
			return;
		}		
		
		List<ErrorInfo> errors = validate(info);						
		
		if (errors.size() > 0) {																																			
			ValidationUtil.showValidationDialog(this, errors, this);
			return;
		}			
		
		if (_visitNo == -1) {						
			_visitNo = _dsarDB.generateVisitNo(info.getProspectID()) + 1;							
			info.setVisitNo(_visitNo);
			_dsarDB.add(info);
			addTransactionLog("INSERT", info);
			setResult(Activity.RESULT_OK);
			finish();
		} else {									
			update(info, user);								
		}		
	}		
	
	private void update(DSARInfo info, UserInfo user) {
		info.setVisitNo(_visitNo);
						
		if (isNotInterestedOrRejectedByUM(info)) {
			confirmNotInterestedOrReject(info, user);
		} else {
			
			updateDSAR(info);
			
			_prospectInfo.setUpdateBy(user.getNip());
			_prospectInfo.setUpdateDate(App.getProcessDateTime());			
			
			if (RESULT_APPLICATION.equals(info.getResultOfVisit())) {								
				_prospectInfo.setProgressStatus("PCD");
				_prospectInfo.setProspectFinishTime(App.getProcessDateTime());
				_prospectDB.updateToPCD(_prospectInfo);
				_prospectDB.updateProspectFinishTime(_prospectInfo);				
			} else if ("NEW".equalsIgnoreCase(_prospectInfo.getProgressStatus())) {
				_prospectInfo.setProgressStatus("FLU");
				_prospectDB.updateProgress(_prospectInfo);				
				_prospectInfo.setPipelineFinishTime(info.getFullVisitActual());
				_prospectInfo.setProspectStartTime(info.getFullVisitActual());				
				_prospectDB.updateProspectStartTimeAndPipelineFinishTime(_prospectInfo);				
			}											
			
			if ("FLU".equalsIgnoreCase(_prospectInfo.getProgressStatus()) || "PCD".equalsIgnoreCase(_prospectInfo.getProgressStatus()))
					updateGuCloseDeal(_prospectID, info.getFullVisitActual());
										
			saveProspectProgress();
			
			setResult(Activity.RESULT_OK);
			finish();
		}							
	}
	
	private boolean isNotInterestedOrRejectedByUM(DSARInfo info) {
		return (RESULT_NOT_INTERESTED.equals(info.getResultOfVisit()) ||
				RESULT_REJECTED_BY_UNIT.equals(info.getResultOfVisit()));
	}
	
	private boolean confirmNotInterestedOrReject(final DSARInfo info, final UserInfo user) {					
		String message = RESULT_NOT_INTERESTED.equals(info.getResultOfVisit())?
				"Apakah debitur yakin tidak tertarik untuk aplikasi ini?" :
				"Apakah anda yakin akan menolak prospek ini?";
		new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.confirm)
        .setMessage(message)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
				try {
					updateDSAR(info);
					updateProspectStatusNotInterestedOrRejectedByUM(info, user);					
					
					setResult(Activity.RESULT_OK);
					finish();
				} catch (Exception e) {
					Log.e("AuditUtil", e.toString());
				}															
            }
        })
        .setNegativeButton(R.string.no, null)
        .show();     
		
		return true;
	}	
		
	
	@Override
	public Object onRetainCustomNonConfigurationInstance() {
		return new Object[] { txtDate, txtTime };
	}
	
	private void saveProspectProgress() {
		ProspectProgressInfo progress = new ProspectProgressInfo();
		progress.setProspectID(_prospectInfo.getProspectID());
		progress.setProgressStatus(_prospectInfo.getProgressStatus());
		progress.setEntryBy(_prospectInfo.getUpdateBy());
		progress.setEntryDate(_prospectInfo.getUpdateDate());
		progress.setUpdateBy(_prospectInfo.getUpdateBy());
		progress.setUpdateDate(_prospectInfo.getUpdateDate());			
		
		ProspectProgressDB progDB = new ProspectProgressDB(_db);
		progDB.add(progress);
	}
	
	private void updateProspectStatusNotInterestedOrRejectedByUM(DSARInfo info, UserInfo user) {
		String date = App.getProcessDateTime();
		
		_prospectInfo.setUpdateBy(user.getNip());
		_prospectInfo.setUpdateDate(date);		
		
		if (RESULT_NOT_INTERESTED.equals(info.getResultOfVisit())) {
			_prospectInfo.setProgressStatus("RJD");
			_prospectInfo.setProspectFinishTime(date);
			_prospectInfo.setNotInterestedReason(SpinnerUtil.optionGetSelectedValue(spnReason, defaultOption));
			_prospectDB.updateProspectNotInterested(_prospectInfo);			
		} else if (RESULT_REJECTED_BY_UNIT.equals(info.getResultOfVisit())) {
			_prospectInfo.setProgressStatus("RJU");
			_prospectInfo.setProspectFinishTime(date);
			_prospectInfo.setUmDecision("0");
			_prospectInfo.setUmDecisionNote("");
			_prospectInfo.setUmDecisionDate(date);
			
			_prospectDB.updateProspectKeputusanUM(_prospectInfo);
		}
		
		saveProspectProgress();				
	}
	
	private void updateGuCloseDeal(String id, String date) {		
		HolidayDB hDB = new HolidayDB(_db);		
		
		String guCloseDeal = hDB.addDays(App.processDate, Configs.getGuCloseDeal(this));
		
		Log.d("DSAR", guCloseDeal);		
		_prospectDB.updateGuCloseDeal(id, guCloseDeal);
	}
	
	private void updateDSAR(DSARInfo info) {
		_dsarDB.update(info);			
		
		addTransactionLog("UPDATE", info);		
	}
	
	private void addAuditTrail(DSARInfo info, String nip) throws Exception {		
		AuditDB audit = new AuditDB(_db);
		ArrayList<AuditInfo> list = AuditUtil.getAuditList(DSARInfo.class, _info , info, nip, defaultOption);		
		
		for (AuditInfo item : list) {
			audit.add(item);
		}		
	}
	
	private void addTransactionLog(String actType, DSARInfo info) {
		TransactionLogDB trans = new TransactionLogDB(_db);
		String primaryKey = "N/A";
		try {
			primaryKey = AuditUtil.getPrimaryKeyInfo(info);
		} catch (Exception e) {			
		}		
		trans.add(info.getUpdateBy(), actType, String.format("%s %s", actType, primaryKey));
	}

	public void show(EditText txt) {
		/*
		txtDate = txt;
		DatePickerFragment fr = new DatePickerFragment();
		fr.setTarget(txtDate);
		fr.show(getSupportFragmentManager(), "datePicker");*/		
		
		showDialog(DATE_DIALOG_ID);
	}
		
	/*
    public void showDateDialog(EditText dateDisplay, Calendar date) {
        activeDateDisplay = dateDisplay;
        activeDate = date;
        showDialog(DATE_DIALOG_ID);
    }*/

    private OnDateSetListener dateSetListener = new OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        	String month = monthOfYear + 1 < 10? "0" + (monthOfYear +1) : String.valueOf(monthOfYear+1);
        	String day = dayOfMonth < 10? "0" + dayOfMonth : String.valueOf(dayOfMonth);
        	getDateDisplay().setText(
                    new StringBuilder()                                     
                        .append(day).append("-")
                        .append(month).append("-")
                        .append(year));            
        }
    };
    
    private OnTimeSetListener timeSetListener = new OnTimeSetListener() {		
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {					
			getTimeDisplay().setText(DialogUtil.toTimeString(hourOfDay, minute));            
		}
	};   

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG_ID:
                return createDatePicker();
            case TIME_DIALOG_ID:            	        		
                return createTimePicker(); 
        }
        return null;
    }       
    
    private Dialog createDatePicker() {
    	String date = txtDate.getText().toString();
    	Calendar cal = Calendar.getInstance();
		int day = cal.get(Calendar.DAY_OF_MONTH);
		int month = cal.get(Calendar.MONTH);
		int year = cal.get(Calendar.YEAR);
		
		if (!Str.isNullOrEmpty(date)) {
			try {
				String[] values = date.split("-");
				year = Integer.parseInt(values[2]);
				month = Integer.parseInt(values[1]) -1;
				day = Integer.parseInt(values[0]);
			} catch (Exception e) {					
			}				
		}
		
		Dialog d = new DatePickerDialog(this, dateSetListener, year, month, day);
				
		return d;
    }
    
    private Dialog createTimePicker() {
    	String time = txtTime.getText().toString();
    	Calendar cal = Calendar.getInstance();
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		int minute = cal.get(Calendar.MINUTE);
		
		if (!Str.isNullOrEmpty(time)) {
			try {
				String[] aTime = time.split(":");
				hour = Integer.parseInt(aTime[0]);
				minute = Integer.parseInt(aTime[1]);
			} catch (Exception e) {
			}
		}
		
		return new TimePickerDialog(this, timeSetListener, hour, minute, true);
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);
        Calendar cal = Calendar.getInstance();
        switch (id) {
            case DATE_DIALOG_ID:
            	String date = txtDate.getText().toString();            	
        		int day = cal.get(Calendar.DAY_OF_MONTH);
        		int month = cal.get(Calendar.MONTH);
        		int year = cal.get(Calendar.YEAR);
        		
        		if (!Str.isNullOrEmpty(date)) {
        			try {
        				String[] values = date.split("-");
        				year = Integer.parseInt(values[2]);
        				month = Integer.parseInt(values[1]) -1;
        				day = Integer.parseInt(values[0]);
        			} catch (Exception e) {					
        			}				
        		}
                ((DatePickerDialog) dialog).updateDate(year, month, day);
                break;
            case TIME_DIALOG_ID:
            	String time = txtTime.getText().toString();
            	
        		int hour = cal.get(Calendar.HOUR_OF_DAY);
        		int minute = cal.get(Calendar.MINUTE);
        		
        		if (!Str.isNullOrEmpty(time)) {
        			try {
        				String[] aTime = time.split(":");
        				hour = Integer.parseInt(aTime[0]);
        				minute = Integer.parseInt(aTime[1]);
        			} catch (Exception e) {
        			}
        		}
                ((TimePickerDialog) dialog).updateTime(hour, minute);
                break;
        }
    }

	public EditText getEditText() {		
		return null;
	}	
	
	@Override
	public void onBackPressed() {
		if (_ro) {
			finish();
			return;
		}	
		
		DSARInfo info = getData();
		boolean isChanged = false;
		try {
			isChanged = _info == null?
					AuditUtil.isFormChanged(DSARInfo.class, _info, info, defaultOption, "DATE_VISIT_PLAN"):
					AuditUtil.isFormChanged(DSARInfo.class, _info, info, defaultOption);
		} catch (Exception e) {		
			e.printStackTrace();
		}	
		
		if (!isChanged) {
			finish();
			return;
		}			
							
		new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.confirm)
        .setMessage(R.string.save_changes)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {           
            	dialog.dismiss();
                    
            }
        })
        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {                
                finish();    
            }
        })
        .show();      
	}
	
	/*
	
	private ArrayList<AuditInfo> getAuditList(DSARInfo newObj) {
		ArrayList<AuditInfo> list = new ArrayList<AuditInfo>();				
		
		String primaryKey = String.format("PROSPECT_ID = %s, VISIT_NO = %s",
				newObj.getProspectID(), newObj.getVisitNo());
			
		
		list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "DATE_VISIT_PLAN",
				null, newObj.getDateVisitPlan(), newObj.getUpdateBy(), newObj.getUpdateDate()));		
		list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "DATE_VISIT_ACTUAL",
				null, newObj.getDateVisitActual(), newObj.getUpdateBy(), newObj.getUpdateDate()));			
		list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "JOIN_FIELD_WORK",
				null, newObj.getJoinFieldWork(), newObj.getUpdateBy(), newObj.getUpdateDate()));				
		list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "OBJECTIVE_OF_VISIT",
				null, newObj.getObjectiveOfVisit(), newObj.getUpdateBy(), newObj.getUpdateDate()));				
		list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "RESULT_OF_VISIT",
				null, newObj.getResultOfVisit(), newObj.getUpdateBy(), newObj.getUpdateDate()));		
		list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "REASON",
				null, newObj.getReason(), newObj.getUpdateBy(), newObj.getUpdateDate()));		
		
		return list;
	}
	
	private ArrayList<AuditInfo> getAuditList(DSARInfo oldObj, DSARInfo newObj) {
		ArrayList<AuditInfo> list = new ArrayList<AuditInfo>();				
				
		String primaryKey = String.format("PROSPECT_ID = %s, VISIT_NO = %s",
				oldObj.getProspectID(), oldObj.getVisitNo());
		
		if (oldObj.getDateVisitPlan().equals(newObj.getDateVisitPlan())) {
			list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "DATE_VISIT_PLAN",
					oldObj.getDateVisitPlan(), newObj.getDateVisitPlan(), newObj.getUpdateBy(), newObj.getUpdateDate()));
		}
		
		if (oldObj.getDateVisitActual().equals(newObj.getDateVisitActual())) {
			list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "DATE_VISIT_ACTUAL",
					oldObj.getDateVisitActual(), newObj.getDateVisitActual(), newObj.getUpdateBy(), newObj.getUpdateDate()));
		}
		
		if (oldObj.getJoinFieldWork().equals(newObj.getJoinFieldWork())) {
			list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "JOIN_FIELD_WORK",
					oldObj.getJoinFieldWork(), newObj.getJoinFieldWork(), newObj.getUpdateBy(), newObj.getUpdateDate()));
		}
		
		if (oldObj.getObjectiveOfVisit().equals(newObj.getObjectiveOfVisit())) {
			list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "OBJECTIVE_OF_VISIT",
					oldObj.getObjectiveOfVisit(), newObj.getObjectiveOfVisit(), newObj.getUpdateBy(), newObj.getUpdateDate()));
		}
		
		if (oldObj.getResultOfVisit().equals(newObj.getResultOfVisit())) {
			list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "RESULT_OF_VISIT",
					oldObj.getResultOfVisit(), newObj.getResultOfVisit(), newObj.getUpdateBy(), newObj.getUpdateDate()));
		}
		
		if (oldObj.getReason().equals(newObj.getReason())) {
			list.add(new AuditInfo("UPDATE", "TBL_DSAR", primaryKey, "REASON",
					oldObj.getReason(), newObj.getReason(), newObj.getUpdateBy(), newObj.getUpdateDate()));
		}
		
		return list;
	}*/	
	
	@Override
	protected void onDestroy() {
		unregisterReceiver(logoutReceiver);
		if (_db != null)
			_db.close();
		super.onDestroy();			
	}
	
	@Override
	public void onUserInteraction() {		
		super.onUserInteraction();
		((CustomSessionApplication) getApplication()).touch();
		
		if (App.DEBUG) {			
			Log.d("User Interaction", "User interaction to "+this.toString());			
		}
	}
}
